Chapter 8 2016,7,10


notes

1.length of string.
len('a string')
2.for loop to get letters in string
for i in string
3.slice
if you want to get the letters form a to b in a string, it should be string[a-1,b]
because the first digit is 0 in a string.
4.string is immutable
but if you want to change some specific digit in string, you can use string.replace('the words you want to replace','the words you want to have')
5.find function
def find(strng, ch):
    """
      Find and return the index of ch in strng.
      Return -1 if ch does not occur in strng.
    """
    ix = 0
    while ix < len(strng):
        if strng[ix] == ch:
            return ix
        ix += 1
    return -1
6.split
7.string comparison
(>, <, >=, <=, ==, !=)The six common comparison operators work with strings, evaluating according to lexicographical order. Examples: "apple" < "banana" evaluates to True. "Zeta" <"Appricot" evaluates to False. "Zebra" <= "aardvark" evaluates to True because all upper case letters precede lower case letters.

exercise


1.
(1)y
(2) g
(3) 9
(4) myst
(5) True
(6) True
(7) False
(8) False
(9) False
2.
prefixes = "JKLMNOPQ"
suffix = "ack"
for letter in prefixes:
    if letter == 'O' or letter == 'Q':
        print(letter + 'uack')
    else:
        print(letter + suffix)
3.
def count_fuction(a,char):
    count = 0
    for i in a:
        if i == char:
            count += 1
    return count
print(count_fuction('abccccc','c'))
5.
import string
sentence=''
count=0
a='asd asde asd'
for i in a:
    if i not in string.punctuation:
        sentence=sentence+i
words=sentence.split()
 
for j in words:
    if 'e' in j:
        count += 1
print('your sentence contain',len(words),'words','of which',count,'(',count/len(words),'%) contain an "e".')
 
6.
for i in range(1,13):
    print(i,i*2,i*3,i*4,i*5,i*6,i*7,i*8,i*9,i*10,i*11,i*12)
7.
def reverse(n):
    new=n[::-1]
    return new
print(reverse(abide))
8.
def mirror(n):
    new = n[::-1]
    new = n + new
    return new
9.
def remove_letter(a,char):
    words=''
    for letter in a:
        if letter != char:
            words=words+letter
    return words
print(remove_letter('aabbcc','c'))
10.
def is_palindrome(n):
    if n == n[::-1]:
        return True
    else:
        return False
print(is_palindrome('abcba'))
 
11.
def count(a,char):
    count=0
    n=0
    while n < len(a):
        n=n+1
        if char in a[n+1-len(char):n+1]:
            count=count+1
    return(count)
print(count('aaabbbccc','bc'))
12.
def remove(a,char):
    words=''
    n=0
    while n<len(a):
        n=n+1
        if char in a[n+1-len(char):n+1]:
            words=a[:n+1-len(char)]+a[n+1:len(a)+1]
            break
    return words
print(remove('aaabbbccc','ccc'))
13.
def remove_all(a,char):
    while char in a:
        for i in range(len(a)):
            if char in a[i+1-len(char):i+1]:
                a =a[:i+1-len(char)]+a[i+1:len(a)+1]
    return a
print(remove_all('aaabbbcccccc','cc'))